package com.weiqiao.mall.service.impl;

import com.google.gson.Gson;
import com.mingsoft.util.StringUtil;
import com.mongodb.client.model.Filters;
import com.weiqiao.mall.domain.CarouseEntity;
import com.weiqiao.mall.repository.ISlideshowRepository;
import com.weiqiao.mall.service.ISlideshowService;
import com.weiqiao.mall.service.dto.SlideDTO;
import com.weiqiao.utils.*;
import org.apache.commons.collections.CollectionUtils;
import org.bson.Document;
import org.bson.conversions.Bson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 轮播图服务层
 */
@Service("SlideshowServiceImpl")
public class SlideshowServiceImpl implements ISlideshowService {
    /**
     * 注入轮播图持久化层
     */
    @Autowired
    @Qualifier("SlideshowRepositoryImpl")
    private ISlideshowRepository slideshowRepository;

    @Override
    public CarouseEntity getCarouseInf(Bson filter) {

        CarouseEntity entity = new CarouseEntity();
        String shelf = slideshowRepository.getOneByFilter(filter);
        if (!StringUtil.isBlank(shelf)) {
            entity = new Gson().fromJson(shelf, CarouseEntity.class);
        }
        return entity;
    }

    @Override
    public boolean updateCarouse(Bson filter, String json) {

        return slideshowRepository.updateCarouse(filter, json);
    }

    @Override
    public Map findCarouse(HttpServletRequest request, Pageable pageable) {
        //公司id,轮播图名称过滤
        int company_id = MallUtil.getCompanyId(request);
        String carouse_name = MallUtil.getString(request, "carouse_name", "");
        Document doc = new Document("company_id", company_id).append("delete_flag", 0);
        if (!"".equals(carouse_name)) {
            doc.append("carouse_name", new Document("$regex", carouse_name));
        }
        List<CarouseEntity> carouseList = new ArrayList<>();
        List<String> list = slideshowRepository.findCarouseList(company_id, doc, pageable);
        if (CollectionUtils.isNotEmpty(list)) {
            for (String a : list) {
                CarouseEntity entity = new Gson().fromJson(a, CarouseEntity.class);
                entity.setCreate_time(DateUtil.timestampToString(entity.getCreate_time()));
                carouseList.add(entity);
            }
        }
        //查询总记录数
        int total = this.countSlideshow(new Document("company_id", company_id).append("delete_flag", 0));
        return PageUtil.toPage(carouseList, total);
    }


    @Override
    public int countSlideshow(Bson bson) {
        return slideshowRepository.countByBson(bson);
    }


    @Override
    public List<CarouseEntity> getCarouseList(Bson filter) {
        List<CarouseEntity> shelf = new ArrayList<>();
        List<String> list = slideshowRepository.getCarouseList(filter);
        if (CollectionUtils.isNotEmpty(list)) {
            list.forEach(str -> new Gson().fromJson(str, CarouseEntity.class));
        }
        return shelf;
    }

    @Override
    public List<SlideDTO> getSlideList(HttpServletRequest request) {
        // 公司id
        String id = request.getParameter("company_id");
        int companyId = StringUtils.isInteger(id) ? Integer.parseInt(id) : 0;
        // 查询条件拼装，公司id为当前公司id，未删除
        Document filter = new Document("company_id", companyId).append("delete_flag", 0);
        // 指定字段输出
        Document project = new Document("carouse_id", 1).append("carouse_name", 1);
        List<String> list = slideshowRepository.getCarouseList(filter, project);
        // 返回结果集
        List<SlideDTO> result = new ArrayList<>();
        Gson gson = new Gson();
        // 字串转换，转换为相应的实体类
        list.forEach(info -> result.add(gson.fromJson(info, SlideDTO.class)));
        return result;
    }

    @Override
    public Map deleteById(HttpServletRequest request) {
        //公司id，轮播图id
        int company_id = MallUtil.getCompanyId(request);
        String carouse_id = MallUtil.getString(request, "carouse_id", "");
        Bson filter = Filters.and(Filters.eq("company_id", company_id), Filters.eq("carouse_id", carouse_id));
        Document doc = new Document();
        doc.append("delete_flag", 1);
        boolean bool = slideshowRepository.updateCarouse(filter, doc);
        Map resultMap = new HashMap(2);
        resultMap.put("result", bool);
        if (bool) {
            resultMap.put("msg", "删除成功！");
        } else {
            resultMap.put("msg", "删除失败！");
        }
        return resultMap;
    }

    @Override
    public Map saveSlideshow(CarouseEntity carouse) {
        Map resultMap = new HashMap(2);
        boolean result;
        if (StringUtils.isBlank(carouse.getCarouse_id())) {
            //新增
            String crrentTime = String.valueOf(System.currentTimeMillis());
            carouse.setCarouse_id(crrentTime);
            carouse.setCreate_time(crrentTime);
            carouse.setCreate_id(SecurityUtils.getUserId());
            carouse.setDelete_flag(0);
            String json = new Gson().toJson(carouse);
            result = slideshowRepository.updateCarouse(Filters.eq("carouse_id", crrentTime), json);
        } else {
            //修改(时间格式需要改成时间戳存储到数据库)
            carouse.setCreate_time(String.valueOf(DateUtil.getYMdToTime(carouse.getCreate_time())));
            String json = new Gson().toJson(carouse);
            Document document = Document.parse(json);
            result = slideshowRepository.updateCarouse(Filters.eq("carouse_id", carouse.getCarouse_id()), document);
        }
        resultMap.put("result", result);
        if (result) {
            resultMap.put("msg", "修改成功！");
        } else {
            resultMap.put("result", "修改失败！");
        }
        return resultMap;
    }
}
